import router from './router'
import { getUserInfo } from '@/api/user.js'

router.beforeEach((to, from, next) => {
    const token = localStorage.getItem('b0352-sms-token')
    if (!token) {
        if(to.path == "/login"){
            next()
        }else if(to.path === "/register"){
            next();
        }else{
            next({path:'/login'})
        }
    } else {
        if(to.path === "/login"){
            next();
        }else if(to.path === "/register"){
            next();
        }else {
            const userInfo = localStorage.getItem('b0352-sms-user')
            if (userInfo) {
                next()
            } else {
                getUserInfo(token).then((response) => {
                    const resp = response.data
                    if (resp.flag) {
                        localStorage.setItem('b0352-sms-user', JSON.stringify(resp.data))
                        next()
                    } else {
                        next({ path: '/login' })
                    }
                })
            }
        }//
    }
})